package cn.wuxing.mediation.common.utils.sms;
import cn.hutool.core.io.resource.Resource;
import cn.hutool.core.io.resource.StringResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhengyz
 * created on 2021/11/5
 * 通过省组件接口调用消息服务
 */
@Slf4j
public class IrsMsgSendTest {

    /**
     * 测试 通过省组件接口调用消息服务短信发送
     */
    public static void sendTemplateSms(String phone,String code) {
        try {
            String interfaceCode = "atg.biz.smssend";
            Map<String, Object> queryMap = new HashMap<>();
            JSONObject requestBody = new JSONObject();
            requestBody.put("phoneNumbers", phone);
            requestBody.put("templateCode", "SMS_1735090078");
            requestBody.put("templateParams", "{\"code\":"+ code +"}");
            requestBody.put("signId", "SIGN_1735090176");
            // 如果发送的是上行短信, 则需要填下面这个参数, 否则不需要填
            //requestBody.put("replyMapping", "{\"1\":\"同意\",\"2\":\"驳回\"}");/
            // 调用省组件接口
            sendToIrsComponent(interfaceCode, requestBody, queryMap);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 测试 通过省组件接口调用消息服务自定义短信发送
//     */
//    @Test
//    public void sendCustomSms() {
//        String interfaceCode = "sms_custom_send";
//        Map<String, Object> queryMap = new HashMap<>();
//        JSONObject requestBody = new JSONObject();
//        requestBody.put("phoneNumbers", "18868180520");
//        requestBody.put("contents", "恭喜您中奖了");
//        requestBody.put("signId", "24");
//        // 如果发送的是上行短信, 则需要填下面这个参数, 否则不需要填
//        requestBody.put("replyMapping", "{\"1\":\"同意\",\"2\":\"驳回\"}");
//        // 调用省组件接口
//        sendToIrsComponent(interfaceCode, requestBody, queryMap);
//    }
//
//
//    /**
//     * 测试 通过省组件接口调用消息服务短信查询
//     */
//    @Test
//    public void querySms() {
//        String interfaceCode = "smsquery";
//        Map<String, Object> queryMap = new HashMap<>();
//        queryMap.put("taskId", "33b845ceb25e4******da035c8525e00");
//        JSONObject requestBody = new JSONObject();
//        // 调用省组件接口
//        sendToIrsComponent(interfaceCode, requestBody, queryMap);
//    }
//
//    /**
//     * 测试 通过省组件接口调用上行短信回复结果查询
//     */
//    @Test
//    public void smsUpstreamResult() {
//        String interfaceCode = "smsUpstreamResult";
//        Map<String, Object> queryMap = new HashMap<>();
//        queryMap.put("taskId", "a1318448422******2fbf54bb8f09eb8");
//        JSONObject requestBody = new JSONObject();
//        // 调用省组件接口
//        sendToIrsComponent(interfaceCode, requestBody, queryMap);
//    }
//
//    /**
//     * 测试 通过省组件接口调用消息服务浙政钉2.0消息发送
//     */
//    @Test
//    public void sendTemplateZzd2() {
//        String interfaceCode = "atg.biz.zzd2send";
//        Map<String, Object> queryMap = new HashMap<>();
//        JSONObject requestBody = new JSONObject();
//        requestBody.put("phoneNumbers", "188****0520");
//        requestBody.put("templateCode", "SMS_159012****");
//        requestBody.put("templateParams", "{\"code\":\"346183\",\"param\":\"123456\"}");
//        requestBody.put("signId", "SIGN_158980****");
//        // 调用省组件接口
//        sendToIrsComponent(interfaceCode, requestBody, queryMap);
//    }
//
//    /**
//     * 测试 通过省组件接口调用消息服务浙政钉2.0自定义消息发送
//     */
//    @Test
//    public void sendCustomZzd2() {
//        String interfaceCode = "zzd2_custom_send";
//        Map<String, Object> queryMap = new HashMap<>();
//        JSONObject requestBody = new JSONObject();
//        requestBody.put("phoneNumbers", "18868180520");
//        requestBody.put("contents", "恭喜您中奖了");
//        requestBody.put("signId", "24");
//        // 调用省组件接口
//        sendToIrsComponent(interfaceCode, requestBody, queryMap);
//    }
//
//    /**
//     * 测试 通过省组件接口调用消息服务浙政钉2.0消息查询
//     */
//    @Test
//    public void queryZzd2() {
//        String interfaceCode = "dingtalkquery";
//        Map<String, Object> queryMap = new HashMap<>();
//        queryMap.put("taskId", "977cfd6ec8d04******c016f6ae2e603");
//        JSONObject requestBody = new JSONObject();
//        // 调用省组件接口
//        sendToIrsComponent(interfaceCode, requestBody, queryMap);
//    }


    private static void sendToIrsComponent(String interfaceCode, JSONObject requestBody, Map<String, Object> queryMap) {
        String url = "https://interface.zjzwfw.gov.cn/gateway/component/routing/agent.htm";
        url = appendParamsToUrl(url, queryMap);
        // 组件超市调用消息服务的accessKey和secretKey
        String accessKey = "28653713d6bc41308f5013336a7a2bbc";
        String secretKey = "f14c92c00a3b46f38e04ffee6925e4ce";
        String timestamp = String.valueOf(System.currentTimeMillis());
        String sign = md5(accessKey + secretKey + timestamp);
        HttpRequest postRequest = HttpUtil.createPost(url);
        postRequest.header("zjgxfwxt-interface-code", interfaceCode);
        postRequest.header("zjgxfwxt-access-key", accessKey);
        postRequest.header("zjgxfwxt-sign", sign);
        postRequest.header("zjgxfwxt-time", timestamp);

        postRequest.body(requestBody.toString());
//        Resource resource = new StringResource(requestBody.toString());
//        postRequest.body(resource);

        log.info("request header: " + postRequest.headers());
        log.info("request body: " + requestBody);
        HttpResponse httpResponse = postRequest.execute();
        log.info("response status: " + httpResponse.getStatus());
        log.info("response body: " + httpResponse.body());
    }

    @SneakyThrows
    private static String md5(final String src) {
        MessageDigest md5;
        StringBuilder hexValue = new StringBuilder(32);
        md5 = MessageDigest.getInstance("MD5");
        byte[] byteArray;
        byteArray = src.getBytes(StandardCharsets.UTF_8);
        byte[] md5Bytes = md5.digest(byteArray);
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    private static String appendParamsToUrl(String srcUrl, Map<String, Object> queryParams){
        if(queryParams == null || queryParams.size() == 0){
            return srcUrl;
        }
        StringBuilder sb = new StringBuilder(srcUrl);
        sb.append("?");
        queryParams.forEach((k, v) -> {
            sb.append(k).append("=").append(v).append("&");
        });
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
